package com.matrix.draft.juc.day7;

import com.matrix.draft.juc.util.JucUtil;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * 循环珊栏
 */
public class TestCyclicBarrier {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("任务全部执行完成");
        });
        IntStream.range(0, 3).forEach(i -> {
            pool.execute(() -> {
                try {
                    JucUtil.sleep(2000);
                    barrier.await();
                    JucUtil.sleep(2000);
                    barrier.await();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        });

    }
}
